package tech.aistar.controller.personal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import tech.aistar.entity.personal.User;
import tech.aistar.entity.personal.UserInfo;
import tech.aistar.service.personal.IUserInfoService;
import tech.aistar.service.personal.IUserService;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;


/**
 * Created by LJX on 2019/9/26.
 */
@Controller
@RequestMapping("/user")
public class LoadController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IUserInfoService userInfoService;

    @RequestMapping("/loadView")
    public String loadView() {
        return "personal/load";
    }

    @RequestMapping("/login")
    public String login(User u, String flag, HttpServletResponse resp, HttpServletRequest req) {
        User user = userService.findByName(u.getUsername());
        if (user != null) {
            if (user.getPassword().equals(u.getPassword())) {
                if (flag != null) {
                    String username = u.getUsername();
                    try {
                        username = URLEncoder.encode(URLEncoder.encode(username, "utf-8"), "utf-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    Cookie c = new Cookie("userLogin", username + ":" + u.getPassword());
                    c.setMaxAge(24 * 60 * 60 * 7);//一周免登陆
                    c.setPath("/");
                    resp.addCookie(c);
                } else {
                    Cookie c = new Cookie("userLogin", "");
                    c.setPath("/");
                    resp.addCookie(c);
                }
                UserInfo userInfo = userInfoService.findById(user.getId());
                req.getSession().setAttribute("userInfo", userInfo);
                req.getSession().setAttribute("user", user);
                return "redirect:/foster/index";

            } else {
                return "redirect:/user/loginView?error=1";
            }
        }
        return "redirect:/user/loginView?error=0";
    }


}
